package net.xi.news.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.xi.news.dao.TagMapper;
import net.xi.news.pojo.Tag;
import net.xi.news.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class TagServiceImpl extends ServiceImpl<TagMapper,Tag> implements TagService {

    @Autowired
    private TagMapper tagRespository;



    @Override
    //根据标签名得到标签
    public Tag getTagByName(String name) {
        Map<String,Object> map=new HashMap<>();
        map.put("name",name);
        List<Tag> tags = tagRespository.selectByMap(map);
        if (tags!=null&&tags.size()!=0){
            return tags.get(0);
        }
        return null;
    }

    @Override
    //找到前？标签
    public List<Tag> tagTop(Integer size) {
        Sort.Order order=new Sort.Order(Sort.Direction.DESC, "news.size");
        Pageable pageable =  PageRequest.of(0,size,Sort.by(order));
        Page<Tag> page=new Page<>();
        page.setSize(pageable.getPageSize());
        page.setCurrent(pageable.getPageNumber());
        return tagRespository.selectPage(page,null).getRecords();
    }

    @Override
    public List<Tag> ListTag(String ids) {
        return tagRespository.selectBatchIds(convertToList(ids));
    }

    private List<String> convertToList(String ids){
        List<String> list = new ArrayList<>();
        if (!"".equals(ids) && ids!=null){
            String[] idarray = ids.split(",");
            for (int i=0;i < idarray.length;i++){
                list.add(idarray[i]);
            }
        }
        return list;
    }

    @Override
    public List<Tag> getAllTag() {
        return tagRespository.selectList(null);
    }

    @Transactional
    @Override
    //分页，列出标签
    public Page<Tag> listTag(Pageable pageable) {
        Page<Tag> page=new Page<>();
        page.setSize(pageable.getPageSize());
        page.setCurrent(pageable.getPageNumber());
        return tagRespository.selectPage(page,null);
    }

}
